﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunctionGraph
{
    struct Interval
    {
        public double Val0, Val1;
        public bool Def0, Def1;
        public bool Cont0, Cont1;

        public Interval(double Value1, double Value2)
        {
            this.Val0 = Value1;
            this.Val1 = Value2;
            Def0 = true;
            Def1 = true;
            Cont0 = true;
            Cont1 = true;
        }

        public static Interval Empty = new Interval() { Val0 = double.PositiveInfinity, Val1 = double.NegativeInfinity, Def0 = false, Def1 = false, Cont0 = false, Cont1 = false };
    }

    class IntervalSet
    {
        public List<Interval> Intervals = new List<Interval>();
        public IntervalSet()
        { }
        public IntervalSet(params Interval[] i)
        {
            Intervals.AddRange(i);
        }

        internal IntervalSet Merge()
        {
            if (Intervals.Count > 1)
            {
                IntervalSet rs = new IntervalSet();
                foreach (var interval in Intervals)
                    rs.UnionWith(interval);
                return rs;
            }
            else
                return this;
            
        }

        private void UnionWith(Interval interval)
        {
            for (int i = 0; i<Intervals.Count; i++)
            {
                var v = Intervals[i];
                if (!(v.Val0 > interval.Val1 || v.Val1 < interval.Val0) && v.Def0 == interval.Def0 && v.Def1 == interval.Def1)
                {
                    v.Val0 = Math.Min(v.Val0, interval.Val0);
                    v.Val1 = Math.Max(v.Val1, interval.Val1);
                    v.Cont0 &= interval.Cont0;
                    Intervals[i] = v;
                    return;
                }
            }
            Intervals.Add(interval);
        }

        public bool NotEmpty { get { return Intervals.Count > 0; } }
    }
}
